package com.web;

import com.entity.PageManager;
import com.entity.User;
import com.service.UserService;
import com.utils.EncryptCodeUtils;
import com.utils.WebUtils;
import com.utils.erweima.zxing.QRCodeUtils;

import javax.mail.Session;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@WebServlet("/user")
@MultipartConfig
public class UserServlet extends HttpServlet {

    //用户的逻辑层
    private UserService userService = new UserService();

    //request对象
    private HttpServletRequest request;
    //response对象
    private HttpServletResponse response;

    //不管是post还是get请求，都会进入到service
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //初始化请求和响应
        this.request = request;
        this.response = response;
        String method = request.getParameter("method");
        switch (method) {
            case "toAddPage": toAddPage(); break;
            case "add": addUser(); break;
            case "index": queryUsers(); break;
            case "showPic": showPic(); break;
            case "del": delUser(); break;
            case "queryUser": queryUser(); break;
            case "update": update(); break;
            case "toIndex": toIndex(); break;
            case "queryMe": queryMe(); break;
            case "downPic": downPic(); break;
            case "createQRCode": createQRCode(); break;
            case "indexVIP": queryUsersVIP(); break;
            case "indexVIP1": queryUsersVIP1(); break;
        }
    }

    private void queryUsersVIP1() throws ServletException, IOException {
        PageManager pm = WebUtils.getBean(PageManager.class, request);
        List<User> users = userService.queryUsers(pm);

        int totalCount = userService.queryUserTotalCount();
        pm.setTotalCount(totalCount);//总数据数
        pm.setPages();//设置总页数

        request.setAttribute("users", users);
        request.getSession().setAttribute("Supertube", "S");
        request.getSession().setAttribute("pm", pm);
        request.setAttribute("outerLi", "user");
        request.setAttribute("innerLi", "showUser");
        WebUtils.toRequestPage(request, response, "showUsersVIP");
    }

    private void queryUsersVIP() throws ServletException, IOException {
        PageManager pm = WebUtils.getBean(PageManager.class, request);
        List<User> users = userService.queryUsersVIP(pm);

        int totalCount = userService.queryUserTotalCountVTP();
        pm.setTotalCount(totalCount);//总数据数
        pm.setPages();//设置总页数

        request.setAttribute("users", users);
        request.getSession().setAttribute("Supertube", "T");
        request.getSession().setAttribute("pm", pm);

        request.setAttribute("outerLi", "user");
        request.setAttribute("innerLi", "showUser");
        WebUtils.toRequestPage(request, response, "showUsersVIP");
    }

//    /**
//     * 上传excel的页面
//     */
//    private void toUploadFilesPage() throws ServletException, IOException {
//        WebUtils.toRequestPage(request, response, "dropzone");
//    }
//
//    /**
//     * 文件上传
//     */
//    private void uploadFiles() throws IOException, ServletException {
//        Collection<Part> parts = request.getParts();
//        List<String> paths = new ArrayList<>();
//        String savePath = WebUtils.UPLOAD_FILES_PATH;
//        for (Part part : parts) {
//            String path = null;
//            //不为空的部分存起来
//            if ((path = WebUtils.uploadFile(part, savePath)) != null)
//                paths.add(path);
//        }
//    }

    /**
     * 去后台首页
     */
    private void toIndex() throws ServletException, IOException {
        WebUtils.toRequestPage(request, response,"index");
    }

    /**
     * 跳转到增加界面
     */
    private void toAddPage() throws ServletException, IOException {
        request.setAttribute("outerLi", "user");
        request.setAttribute("innerLi", "showUser");
        WebUtils.toRequestPage(request, response, "addUser");
    }

//    /**
//     * 导入数据
//     */
//    private void importExcel() throws IOException, ServletException {
//        String path = WebUtils.uploadFile(request, "file", WebUtils.UPLOAD_FILES_PATH);
//        List<User> users = ExcelUtils.readExcel(User.class, path);
//        //统计成功了多少条
//        int count = 0;
//        //将数据保存到数据库
//        for (User user : users) {
//            if (userService.addUser(user)) count++;
//        }
//        //转发到首页
//        request.getSession().setAttribute("msg", "成功导入"+count+"条数据");
//        request.getSession().setAttribute("result", true);
//        response.sendRedirect("user?method=index");
//    }

//    /**
//     * 导出报表
//     */
//    private void exportExcel() {
//        //获取数据
//        List<User> users = userService.queryUsers();
//        try {
//            //转化数据
//            Object[][] data = ExcelUtils.listToArrs(User.class, users);
//            //自定义表头
//            String[] headers = {"编号", "用户名","密码", "姓名","性别","年龄","生日","电话","身高", "头像地址"};
//            //创建excel
//            String path = ExcelUtils.createExcel("xlsx",
//                    WebUtils.ROOT_PATH + "/userExcel", headers, data, "用户数据");
//            path = path.replaceAll("\\\\", "/");
//            //重定向到下载图片
//            response.sendRedirect("user?method=downPic&pic="+ URLEncoder.encode(path, "UTF-8"));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }

    /**
     * 生成二维码
     */
    private void createQRCode() throws IOException {
        int id = WebUtils.parseInt(request.getParameter("id"));
        User user = userService.queryUser(id);
        //拼接保存路径
        String path = WebUtils.SAVE_PATH_QRCODE + "/" + user.getUsername() + ".png";
        path = path.replaceAll("\\\\", "/");
        //拼接内容
        String content = "编号：" + id +
                "\n用户名：" + user.getUsername() +
                "\n密码：" + user.getPassword() +
                "\n姓名：" + user.getName() +
                "\n盐值：" + user.getPhone() +
                "\n图片地址：'" + user.getPic();
        //生成二维码
        QRCodeUtils.createQRCodeZxing(content, path);
        //将内容写入到前端
        WebUtils.sendMSG(response, path);
    }

    /**
     * 根据图片地址下载图片
     */
    private void downPic() {
        String pic = request.getParameter("pic");
        File file = new File(pic);
        if (!file.exists()) return;
        try {
            //文件的输入流，用来读取
            InputStream in = new BufferedInputStream(new FileInputStream(file));
            //输出流
            OutputStream out = response.getOutputStream();
            //获取文件名
            //new String("菲梦伊连衣裙.png".getBytes("utf-8"),"ISO-8859-1")
            String filename = pic.substring(pic.lastIndexOf("/")+1);
            filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
            response.setHeader("content-disposition", "attachment;filename=\"" + filename +"\"");
            //将字节流写
            int len = 0;
            byte[] b = new byte[1024];
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
            //刷新与释放资源
            out.flush();
            response.flushBuffer();
            out.close();
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询自己的个人信息
     */
    private void queryMe() throws ServletException, IOException {
        int id = WebUtils.parseInt(request.getParameter("id"));
        User user = userService.queryUser(id);
        request.setAttribute("user", user);
        request.setAttribute("outerLi", "system");
        request.setAttribute("innerLi", "showMe");
        WebUtils.toRequestPage(request, response, "showMe");
    }

    /**
     * 修改数据
     */
    private void update() throws IOException, ServletException {
        User user = WebUtils.getBean(User.class, request);
        String path = WebUtils.uploadFile(request, "newPic", WebUtils.SAVE_PATH);
        //如果path是空，新的图片没上传，不做修改
        user.setPic(path==null?user.getPic():path);

        String password = user.getPassword();
        if (password != null && !password.equals("")) {
            //密码不为空的时候，证明用户修改过密码，重新设置密码
            //设置盐值
            user.setPhone(WebUtils.getRandomString());
            //重新设置密码
            user.setPassword(EncryptCodeUtils.getEncryptStr(user.getPassword(),
                    user.getPhone()));
        } else {
            //通过用户名重新查询一遍用户，得到这个密码和盐值
            User queryUser = userService.queryUserByUsername(user.getUsername());
            //设置密码
            user.setPassword(queryUser.getPassword());
            //重新设置盐值
            user.setPhone(queryUser.getPhone());
        }
        user.setAdministrators("T");
        user.setSupertube("F");
        //修改
        boolean result = userService.updateUser(user);
        PageManager pm = (PageManager) request.getSession().getAttribute("pm");
        request.getSession().setAttribute("msg", result?"修改成功":"修改失败");
        request.getSession().setAttribute("result", result);
        User loginUser = (User) request.getSession().getAttribute("user");
        if (result && loginUser.getId() == user.getId()) {
            request.getSession().setAttribute("user", user);
        }

        response.sendRedirect("user?method=index&pn="+(pm==null?"":pm.getPn()));
    }

    /**
     * 查询单个用户数据
     */
    private void queryUser() throws ServletException, IOException {
        int id = WebUtils.parseInt(request.getParameter("id"));
        User user = userService.queryUser(id);
        request.setAttribute("user", user);
        request.setAttribute("outerLi", "user");
        request.setAttribute("innerLi", "showUser");
        WebUtils.toRequestPage(request, response, "updateUser");
    }

    /**
     * 根据用户编号删除用户信息
     */
    private void delUser() throws IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        PageManager pm = (PageManager) request.getSession().getAttribute("pm");
        if (pm != null) {
            pm.setTotalCount(pm.getTotalCount()-1);
            pm.setPages();
            //删除之后，正好最后一页没了，直接使用最后一页当作当前页
            pm.setPn(pm.getPn()>=pm.getPages()?pm.getPages():pm.getPn());
        }
        boolean result = userService.delUser(id);
        request.getSession().setAttribute("msg", result?"删除成功":"删除失败");
        request.getSession().setAttribute("result", result);
        response.sendRedirect("user?method=index&pn="+((pm==null)?"":pm.getPn()));
    }

    /**
     * 显示图片
     */
    private void showPic() throws IOException {
        String pic = request.getParameter("pic");
        File file = new File(pic);
        //将图片的字节写入到页面
        //jsp中的out写入东西
        OutputStream out = response.getOutputStream();
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        byte[] b = new byte[1024];
        int len = 0;
        while ((len = in.read(b)) != -1) {
            out.write(b, 0, len);
        }
        out.flush();
        out.close();
        in.close();
        response.flushBuffer();//刷新缓存
    }

    /**
     * 查询所有数据
     */
    private void queryUsers() throws ServletException, IOException {
        PageManager pm = WebUtils.getBean(PageManager.class, request);
        List<User> users = userService.queryUsers(pm);

        int totalCount = userService.queryUserTotalCount();
        pm.setTotalCount(totalCount);//总数据数
        pm.setPages();//设置总页数

        request.setAttribute("users", users);
        request.getSession().setAttribute("Supertube", "F");
        request.getSession().setAttribute("pm", pm);
        request.setAttribute("outerLi", "user");
        request.setAttribute("innerLi", "showUser");
        WebUtils.toRequestPage(request, response, "showUsers");
    }

    /**
     * 增加用户数据
     */
    private void addUser() throws ServletException, IOException {
        //转化为实体类
        User user = WebUtils.getBean(User.class, request);

        //设置盐值
        user.setPhone(WebUtils.getRandomString());
        //重新设置密码
        user.setPassword(EncryptCodeUtils.getEncryptStr(user.getPassword(),
                user.getPhone()));

        PageManager pm = (PageManager) request.getSession().getAttribute("pm");
        if (pm != null) {
            pm.setTotalCount(pm.getTotalCount()+1);
            pm.setPages();
        }

        //重新设置文件路径
        user.setPic(WebUtils.uploadFile(request, "pic", WebUtils.SAVE_PATH));
        user.setAdministrators("T");
        user.setSupertube("F");
        boolean result = userService.addUser(user);
        request.getSession().setAttribute("msg", result?"增加成功":"增加失败");
        request.getSession().setAttribute("result", result);
        response.sendRedirect("user?method=indexVIP&pn="+(pm==null?"":pm.getPages()));
    }
}
